<template>
    <view class="index-container" :class="{'care-mode': careMode}">
      <view class="header">
        <view class="header-content">
          <text class="welcome">欢迎回来，{{ studentName }}</text>
          <view class="button-group">
            <button class="care-mode-btn" @click="toggleCareMode">{{ careMode ? '退出关怀模式' : '关怀模式' }}</button>
            <button class="logout-btn" @click="handleLogout">退出登录</button>
          </view>
        </view>
      </view>
      
      <view class="content" v-if="activeTab === 'course' && !currentConversation">
        <!-- 课程中心内容 -->
        <view class="course-section">
          <text class="section-title">进行中的课程</text>
          <view v-if="uncompletedCourses.length > 0" class="course-list">
            <view v-for="(course, index) in uncompletedCourses" :key="course.id" class="course-item">
              <view class="course-info">
                <text class="course-title">{{ course.title }}</text>
                <text class="course-desc">{{ course.progress }}% 已完成</text>
              </view>
              <view class="progress-bar">
                <view class="progress-fill" :style="{width: course.progress + '%'}"></view>
              </view>
            </view>
          </view>
          <view v-else class="empty-tip">
            <text>暂无进行中的课程</text>
          </view>
        </view>

        <view class="course-section">
          <text class="section-title">已完成的课程</text>
          <view v-if="completedCourses.length > 0" class="course-list">
            <view v-for="(course, index) in completedCourses" :key="course.id" class="course-item completed">
              <view class="course-info">
                <text class="course-title">{{ course.title }}</text>
                <text class="course-desc">已完成</text>
              </view>
              <view class="progress-bar">
                <view class="progress-fill" style="width: 100%"></view>
              </view>
            </view>
          </view>
          <view v-else class="empty-tip">
            <text>暂无已完成的课程</text>
          </view>
        </view>

        <!-- 活跃度统计 -->
        <view class="course-section">
          <view class="section-header">
            <text class="section-title">您的活跃度</text>
            <text class="date-range">{{ currentDateRange }}</text>
          </view>
          
          <!-- 活跃度图表 -->
          <view class="activity-chart">
            <view class="chart-container">
              <view class="chart-placeholder">
                <!-- 由于uni-app不支持直接使用echarts，这里使用简化的柱状图 -->
                <view class="chart-bars">
                  <view v-for="(value, index) in activityData.data" :key="index" class="chart-bar-item">
                    <view class="chart-bar" :style="{ height: value + 'px' }"></view>
                    <text class="chart-label">{{ activityData.labels[index] }}</text>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 活跃度统计数据 -->
            <view class="activity-stats">
              <view class="stat-item">
                <text class="stat-value">{{ activityStats.totalMinutes }}</text>
                <text class="stat-label">总学习时长(分钟)</text>
              </view>
              <view class="stat-item">
                <text class="stat-value">{{ activityStats.averageMinutes }}</text>
                <text class="stat-label">日均学习时长(分钟)</text>
              </view>
              <view class="stat-item">
                <text class="stat-value">{{ activityStats.maxMinutes }}</text>
                <text class="stat-label">最长学习时长(分钟)</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="content" v-if="activeTab === 'homework' && !currentConversation">
        <view class="homework-section">
          <text class="section-title">待办作业</text>
          <view v-if="pendingAssignments.length > 0" class="homework-list">
            <view 
              v-for="(assignment, index) in pendingAssignments" 
              :key="assignment.questionId" 
              class="homework-item"
              @click="goToAssignment(assignment)"
            >
              <view class="homework-icon" :style="{ backgroundColor: ['#FFE2E5', '#FFF4DE', '#DCFCE7', '#F3E8FF'][index % 4] }">
                <text class="homework-icon-text">作业</text>
              </view>
              <view class="homework-content">
                <text class="homework-title">{{ assignment.title }}</text>
                <text class="homework-course">{{ assignment.courseName }}</text>
                <text class="homework-deadline" v-if="assignment.deadline">
                  截止日期: {{ formatDate(assignment.deadline) }}
                </text>
              </view>
              <text class="homework-arrow">›</text>
            </view>
          </view>
          <view v-else class="empty-tip">
            <text>暂无待办作业</text>
          </view>
        </view>
      </view>

      <!-- 消息中心内容 -->
      <view class="content" v-if="activeTab === 'message' && !currentConversation">
        <!-- 消息中心顶部导航 -->
        <view class="message-tabs">
          <view class="message-tab-item" 
                :class="{ active: currentMessageTab === 0 }" 
                @click="currentMessageTab = 0">
            <view class="tab-content">
              <image class="tab-icon" src="../static/images/好友.png"></image>
              <text class="tab-text">好友</text>
            </view>
          </view>
          <view class="message-tab-item" 
                :class="{ active: currentMessageTab === 1 }" 
                @click="currentMessageTab = 1">
            <view class="tab-content">
              <image class="tab-icon" src="../static/images/群聊.png"></image>
              <text class="tab-text">群聊</text>
            </view>
          </view>
          <view class="message-tab-item" 
                :class="{ active: currentMessageTab === 2 }" 
                @click="currentMessageTab = 2">
            <view class="tab-content">
              <image class="tab-icon" src="../static/images/通知.png"></image>
              <text class="tab-text">通知</text>
            </view>
          </view>
        </view>

        <!-- 消息列表区域 -->
        <view class="message-content">
          <!-- 好友列表 -->
          <template v-if="currentMessageTab === 0">
            <view v-for="friend in friends" :key="friend.id" 
                  class="chat-item" 
                  @click="openPrivateChat(friend)">
              <view class="avatar">{{ friend.name?.[0] || 'U' }}</view>
              <view class="chat-info">
                <view class="top-line">
                  <text class="name">{{ friend.name }}</text>
                  <text class="time" v-if="getLastMessage(friend.id)">
                    {{ formatTime(getLastMessage(friend.id).createdAt) }}
                  </text>
                </view>
                <text class="last-message" v-if="getLastMessage(friend.id)">
                  {{ getLastMessage(friend.id).content }}
                </text>
              </view>
            </view>
          </template>

          <!-- 群聊列表 -->
          <template v-if="currentMessageTab === 1">
            <view v-for="group in groups" :key="group.id" 
                  class="chat-item" 
                  @click="openGroupChat(group)">
              <view class="avatar group-avatar">{{ group.name?.[0] || 'G' }}</view>
              <view class="chat-info">
                <view class="top-line">
                  <text class="name">{{ group.name }}</text>
                  <text class="time" v-if="getLastGroupMessage(group.id)">
                    {{ formatTime(getLastGroupMessage(group.id).createdAt) }}
                  </text>
                </view>
                <text class="last-message" v-if="getLastGroupMessage(group.id)">
                  {{ getLastGroupMessage(group.id).content }}
                </text>
              </view>
            </view>
          </template>

          <!-- 通知列表 -->
          <template v-if="currentMessageTab === 2">
            <view v-for="notice in notifications" :key="notice.id" 
                  class="chat-item notice-item" 
                  @click="handleNotification(notice)">
              <view class="avatar notice-avatar">
                <text class="iconfont icon-notification"></text>
              </view>
              <view class="chat-info">
                <view class="top-line">
                  <text class="name">{{ notice.title }}</text>
                  <text class="time">{{ formatTime(notice.createdAt) }}</text>
                </view>
                <text class="last-message">{{ notice.content }}</text>
              </view>
            </view>
          </template>
        </view>
      </view>

      <!-- 聊天详情页面 -->
      <view class="chat-detail" v-if="currentConversation">
        <!-- 聊天头部 -->
        <view class="chat-header">
          <view class="back-button" @click="closeChat">
            <text class="iconfont icon-back">返回</text>
          </view>
          <view class="chat-title">
            <text>{{ currentConversation.targetUser?.name || currentConversation.title }}</text>
            <text v-if="currentConversation.targetUser?.role === 2" class="role-tag">【老师】</text>
          </view>
          <view class="header-actions">
            <text class="iconfont icon-more" @click="showMoreOptions"></text>
          </view>
        </view>

        <!-- 消息列表 -->
        <scroll-view 
          class="message-list" 
          scroll-y 
          :scroll-top="scrollTop"
          @scrolltoupper="loadMoreMessages"
          :refresher-enabled="true"
          :refresher-triggered="isRefreshing"
          @refresherrefresh="onRefresh"
          :id="'message-list'"
        >
          <view class="message-wrapper">
            <view v-for="(msg, index) in messages" 
                  :key="index" 
                  class="message-item"
                  :class="{'self': msg.senderId === currentUser?.id}"
            >
              <view class="message-avatar">
                {{ msg.senderName?.[0] || 'U' }}
              </view>
              <view class="message-content">
                <view class="sender-name">
                  {{ msg.senderName || '未知用户' }}
                  <text v-if="msg.senderRole === 2" class="role-tag">【老师】</text>
                </view>
                
                <!-- 语音消息 -->
                <view v-if="msg.messageType === 'AUDIO'" class="audio-message" @click="playAudio(msg.content)">
                  <text class="iconfont icon-voice"></text>
                  <text class="audio-duration">【语音消息请在网页版查看】</text>
                </view>
                
                <!-- 文本消息 -->
                <view v-else class="text-message">
                  {{ msg.content }}
                </view>
                
                <view class="message-time">{{ formatTime(msg.createdAt) }}</view>
              </view>
            </view>
          </view>
        </scroll-view>

        <!-- 输入区域 -->
        <view class="input-area" v-if="!isUserMuted">
          <!-- <view v-if="isRecording" class="recording-indicator">
            <text>正在录音...</text>
            <button type="warn" size="mini" @click="stopRecording">停止</button>
          </view> -->
          <view class="input-wrapper">
            <textarea
              class="message-input"
              :value="messageInput"
              @input="handleInput"
              :adjust-position="false"
              :show-confirm-bar="false"
              :cursor-spacing="20"
              :fixed="true"
              placeholder="输入消息..."
              @confirm="sendMessage"
            ></textarea>
            <view class="input-actions">
              <button 
                class="send-button" 
                type="primary" 
                size="mini"
                @click="sendMessage"
                :disabled="!messageInput.trim()"
              >
              发送</button>
            </view>
          </view>
        </view>
        <view v-else class="muted-tip">
          <text>您已被禁言</text>
        </view>
      </view>

      <!-- 底部导航栏 -->
      <view class="tabbar" v-if="!currentConversation">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'course' }" 
          @click="switchTab('course')"
        >
          <image class="tab-icon" src="../static/images/课程中心.png"></image>
          <text class="tab-text">课程中心</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'homework' }" 
          @click="switchTab('homework')"
        >
          <image class="tab-icon" src="../static/images/作业中心.png"></image>
          <text class="tab-text">作业中心</text>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'message' }" 
          @click="switchTab('message')"
        >
          <image class="tab-icon" src="../static/images/消息中心.png"></image>
          <text class="tab-text">消息中心</text>
        </view>
      </view>
    </view>
</template>
  
<script>
export default {
  data() {
    return {
      studentName: '',
      userId: null,
      activeTab: 'course',
      currentMessageTab: 0,
      friends: [],
      groups: [],
      notifications: [],
      socket: null,
      lastMessages: {},
      uncompletedCourses: [],
      completedCourses: [],
      likedCourses: [],
      stats: {
        totalCourses: 0,
        completedCourses: 0,
        totalHours: 0
      },
      baseUrl: 'http://localhost:8080',
      activityData: {
        labels: [],
        data: []
      },
      activityStats: {
        totalMinutes: 0,
        averageMinutes: 0,
        maxMinutes: 0
      },
      currentDateRange: '',
      currentConversation: null,
      scrollTop: 0,
      isRefreshing: false,
      isRecording: false,
      messageInput: '',
      currentUser: null,
      isUserMuted: false,
      messages: [],
      currentPage: 1,
      pageSize: 20,
      hasMoreMessages: false,
      recordingStartTime: 0,
      recorderManager: null,
      careMode: false,
      pendingAssignments: []
    }
  },
  onLoad() {
    // 获取用户信息
    this.getUserInfo();
    
    // 设置日期范围
    this.setDateRange();
    
    // 检查是否已启用关怀模式
    this.checkCareMode();
  },
  methods: {
    // 检查是否已启用关怀模式
    checkCareMode() {
      try {
        const careModeStatus = uni.getStorageSync('careMode');
        if (careModeStatus === 'true') {
          this.careMode = true;
          this.applyCareMode();
        }
      } catch (e) {
        console.error('获取关怀模式状态失败', e);
      }
    },
    
    // 切换关怀模式
    toggleCareMode() {
      this.careMode = !this.careMode;
      
      // 保存关怀模式状态到本地存储
      uni.setStorageSync('careMode', this.careMode.toString());
      
      if (this.careMode) {
        this.applyCareMode();
      } else {
        this.removeCareMode();
      }
      
      // 更新UI
      this.updateCareUI();
    },
    
    // 应用关怀模式
    applyCareMode() {
      // 设置全局样式
      uni.setTabBarStyle({
        color: '#999999',
        selectedColor: '#ff3300',
        backgroundColor: '#ffffff',
        borderStyle: 'black'
      });
      
      // 设置导航栏样式
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#ff3300'
      });
      
      // 保存当前为关怀模式
      this.$set(this, 'careMode', true);
      
      // 通知用户已开启关怀模式
      uni.showToast({
        title: '已开启关怀模式',
        icon: 'success'
      });
    },
    
    // 移除关怀模式
    removeCareMode() {
      // 恢复默认样式 - 使用第一次生成的关怀模式样式
      uni.setTabBarStyle({
        color: '#999999',
        selectedColor: '#ff6b00',
        backgroundColor: '#ffffff',
        borderStyle: 'black'
      });
      
      // 恢复导航栏样式
      uni.setNavigationBarColor({
        frontColor: '#ffffff',
        backgroundColor: '#4CAF50'
      });
      
      // 保存当前为非关怀模式
      this.$set(this, 'careMode', false);
      
      // 通知用户已关闭关怀模式
      uni.showToast({
        title: '已关闭关怀模式',
        icon: 'success'
      });
    },
    
    // 更新关怀模式UI
    updateCareUI() {
      // 使用nextTick确保DOM已更新
      this.$nextTick(() => {
        // 更新字体和颜色
        if (this.careMode) {
          // 增加字体间距
          uni.getSystemInfo({
            success: (res) => {
              if (res.platform === 'android' || res.platform === 'ios') {
                // 移动端可以使用动态样式
                try {
                  // 检查plus对象是否可用
                  if (typeof plus !== 'undefined' && plus.webview) {
                    plus.webview.currentWebview().setStyle({
                      letterSpacing: '0.08em'
                    });
                  }
                } catch (e) {
                  console.error('设置字体间距失败:', e);
                }
              }
            }
          });
        } else {
          // 非关怀模式也应用一些样式
          uni.getSystemInfo({
            success: (res) => {
              if (res.platform === 'android' || res.platform === 'ios') {
                try {
                  if (typeof plus !== 'undefined' && plus.webview) {
                    plus.webview.currentWebview().setStyle({
                      letterSpacing: '0.05em'
                    });
                  }
                } catch (e) {
                  console.error('设置字体间距失败:', e);
                }
              }
            }
          });
        }
      });
    },
    
    // 设置日期范围
    setDateRange() {
      const now = new Date();
      const lastWeek = new Date(now);
      lastWeek.setDate(now.getDate() - 6);
      
      // 格式化日期
      const formatDate = (date) => {
        const month = date.getMonth() + 1;
        const day = date.getDate();
        return `${month}月${day}日`;
      };
      
      this.currentDateRange = `${formatDate(lastWeek)} - ${formatDate(now)}`;
    },
    
    // 获取用户信息
    getUserInfo() {
      try {
        const userInfo = uni.getStorageSync('userInfo');
        if (userInfo) {
          const info = JSON.parse(userInfo);
          this.studentName = info.name || info.username;
          
          // 获取用户ID
          this.userId = info.id || info.userId;
          
          // 如果没有获取到用户ID，尝试从localStorage获取
          if (!this.userId) {
            this.userId = uni.getStorageSync('userId');
          }
          
          // 如果仍然没有获取到，则使用默认值
          if (!this.userId) {
            console.warn('未找到用户ID，使用默认值');
            this.userId = 1;
          }
          
          // 存储用户信息到currentUser
          this.currentUser = {
            id: this.userId,
            name: this.studentName,
            role: info.role || 1
          };
          
          // 存储用户ID到localStorage
          uni.setStorageSync('userId', this.userId);
          
          // 加载课程数据
          this.loadAllCourseData();
        }
      } catch (e) {
        console.error('获取用户信息失败', e);
      }
    },
    
    // 加载所有课程数据
    loadAllCourseData() {
      // 获取未完成课程
      this.getUncompletedCourses();
      
      // 获取已完成课程
      this.getCompletedCourses();
      
      // 获取收藏课程
      this.getLikedCourses();
      
      // 获取学生课程列表（用于统计）
      this.getStudentCourses();
      
      // 获取活跃度数据
      this.getActivityData();
    },
    
    // 获取未完成课程
    getUncompletedCourses() {
      uni.request({
        url: `${this.baseUrl}/api/student/center/subscribed-uncompleted`,
        method: 'GET',
        data: {
          studentId: this.userId
        },
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          // 检查响应是否有数据
          if (res.data && res.data.data) {
            console.log('获取未完成课程成功:', res.data);
            this.uncompletedCourses = res.data.data || [];
            this.calculateStats();
          } else {
            console.error('获取未完成课程失败:', res.data);
            this.uncompletedCourses = [];
          }
        },
        fail: (err) => {
          console.error('请求未完成课程失败:', err);
          this.uncompletedCourses = [];
        }
      });
    },
    
    // 获取已完成课程
    getCompletedCourses() {
      uni.request({
        url: `${this.baseUrl}/api/student/center/subscribed-completed`,
        method: 'GET',
        data: {
          studentId: this.userId
        },
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          // 检查响应是否有数据
          if (res.data && res.data.data) {
            console.log('获取已完成课程成功:', res.data);
            this.completedCourses = res.data.data || [];
            this.calculateStats();
          } else {
            console.error('获取已完成课程失败:', res.data);
            this.completedCourses = [];
          }
        },
        fail: (err) => {
          console.error('请求已完成课程失败:', err);
          this.completedCourses = [];
        }
      });
    },
    
    // 获取收藏课程
    getLikedCourses() {
      uni.request({
        url: `${this.baseUrl}/api/student/center/liked-courses`,
        method: 'GET',
        data: {
          studentId: this.userId
        },
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          // 检查响应是否有数据
          if (res.data && res.data.data) {
            console.log('获取收藏课程成功:', res.data);
            this.likedCourses = res.data.data || [];
            this.calculateStats();
          } else {
            console.error('获取收藏课程失败:', res.data);
            this.likedCourses = [];
          }
        },
        fail: (err) => {
          console.error('请求收藏课程失败:', err);
          this.likedCourses = [];
        }
      });
    },
    
    // 获取学生课程列表
    getStudentCourses() {
      uni.request({
        url: `${this.baseUrl}/api/studentcourse/${this.userId}/courses`,
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          // 检查响应是否有数据
          if (res.data && res.data.data) {
            console.log('获取学生课程列表成功:', res.data);
            // 获取课程列表成功，用于计算统计数据
            const courses = res.data.data || [];
            this.calculateStatsFromCourses(courses);
          } else {
            console.error('获取学生课程列表失败:', res.data);
          }
        },
        fail: (err) => {
          console.error('请求学生课程列表失败:', err);
        }
      });
    },
    
    // 获取活跃度数据
    getActivityData() {
      uni.request({
        url: `${this.baseUrl}/api/student/center/activity`,
        method: 'GET',
        data: {
          studentId: this.userId,
          days: 7
        },
        header: {
          'content-type': 'application/json'
        },
        success: (res) => {
          if (res.data && res.data.data) {
            console.log('获取活跃度数据成功:', res.data);
            this.activityData.labels = res.data.data.labels || [];
            this.activityData.data = res.data.data.data || [];
            
            // 计算统计数据
            if (this.activityData.data.length > 0) {
              const totalMinutes = this.activityData.data.reduce((sum, val) => sum + val, 0);
              this.activityStats = {
                totalMinutes,
                averageMinutes: Math.round(totalMinutes / this.activityData.data.length),
                maxMinutes: Math.max(...this.activityData.data)
              };
            } else {
              // 清空统计数据
              this.activityStats = {
                totalMinutes: 0,
                averageMinutes: 0,
                maxMinutes: 0
              };
            }
          } else {
            console.error('获取活跃度数据失败:', res.data);
            // 清空数据
            this.activityData = {
              labels: [],
              data: []
            };
            this.activityStats = {
              totalMinutes: 0,
              averageMinutes: 0,
              maxMinutes: 0
            };
          }
        },
        fail: (err) => {
          console.error('请求活跃度数据失败:', err);
          // 清空数据
          this.activityData = {
            labels: [],
            data: []
          };
          this.activityStats = {
            totalMinutes: 0,
            averageMinutes: 0,
            maxMinutes: 0
          };
        }
      });
    },
    
    // 根据课程列表计算统计数据
    calculateStatsFromCourses(courses) {
      const totalCourses = courses.length;
      let completedCourses = 0;
      let totalHours = 0;
      
      courses.forEach(course => {
        if (course.progress >= 100) {
          completedCourses++;
        }
        
        // 计算学习时长（假设每个课程有duration属性，单位为小时）
        if (course.duration) {
          totalHours += course.duration * (course.progress / 100);
        }
      });
      
      this.stats = {
        totalCourses,
        completedCourses,
        totalHours: Math.round(totalHours)
      };
    },
    
    // 计算统计数据
    calculateStats() {
      const totalCourses = this.uncompletedCourses.length + this.completedCourses.length;
      const completedCourses = this.completedCourses.length;
      
      // 计算总学习时长（假设每个课程有duration属性，单位为小时）
      let totalHours = 0;
      this.uncompletedCourses.forEach(course => {
        if (course.duration) {
          totalHours += course.duration * (course.progress / 100);
        }
      });
      
      this.completedCourses.forEach(course => {
        if (course.duration) {
          totalHours += course.duration;
        }
      });
      
      this.stats = {
        totalCourses,
        completedCourses,
        totalHours: Math.round(totalHours)
      };
    },
    
    goToChat() {
      uni.navigateTo({
        url: '/pages/chat'
      });
    },
    
    switchTab(tab) {
      this.activeTab = tab;
      if (tab === 'message') {
        // 初始化消息中心的数据
        this.initializeMessageCenter();
      } else if (tab === 'homework') {
        // 加载待办作业
        this.loadPendingAssignments();
      }
    },
    
    handleLogout() {
      uni.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储的用户信息
            uni.removeStorageSync('satoken');
            uni.removeStorageSync('userId');
            uni.removeStorageSync('username');
            uni.removeStorageSync('name');
            uni.removeStorageSync('role');
            uni.removeStorageSync('userInfo');
            
            // 跳转到登录页面
            uni.reLaunch({
              url: '/pages/login'
            });
          }
        }
      });
    },

    // 添加消息中心初始化方法
    initializeMessageCenter() {
      // 获取用户信息
      const token = uni.getStorageSync('satoken');
      const userId = uni.getStorageSync('userid');
      
      if (token && userId) {
        // 获取好友列表
        this.fetchFriends();
        // 获取群聊列表
        this.fetchGroups();
        // 获取通知列表
        this.fetchNotifications();
        // 连接WebSocket
        this.connectWebSocket();
      }
    },

    // WebSocket连接
    connectWebSocket() {
      const token = uni.getStorageSync('satoken');
      if (!token) return;
      
      if (this.socket) {
        console.log('WebSocket已连接，无需重复创建');
        return;
      }
      
      this.socket = uni.connectSocket({
        url: `ws://localhost:8080/api/ws/chat?token=${token}`,
        success: () => {
          console.log('WebSocket连接请求成功');
        }
      });

      this.socket.onOpen(() => {
        console.log('WebSocket连接已打开');
      });

      this.socket.onMessage((res) => {
        console.log('收到WebSocket消息:', res.data);
        const message = JSON.parse(res.data);
        
        // 如果当前在聊天界面，且消息属于当前会话，则添加到消息列表
        if (this.currentConversation) {
          const currentConvId = this.currentConversation.id || this.currentConversation.conversation?.id;
          if (message.conversationId === currentConvId) {
            this.messages = [...this.messages, message];
            this.$nextTick(() => {
              setTimeout(() => {
                this.scrollToBottom();
              }, 300);
            });
          }
        }
        
        // 更新最后一条消息和未读数
        if (message.type === 'PRIVATE') {
          const friendId = message.senderId === this.userId ? message.receiverId : message.senderId;
          this.lastMessages[`private_${friendId}`] = message;
          if (message.senderId !== this.userId) {
            this.unreadCounts[`private_${friendId}`] = (this.unreadCounts[`private_${friendId}`] || 0) + 1;
          }
        } else if (message.type === 'GROUP') {
          this.lastMessages[`group_${message.conversationId}`] = message;
          if (message.senderId !== this.userId) {
            this.unreadCounts[`group_${message.conversationId}`] = (this.unreadCounts[`group_${message.conversationId}`] || 0) + 1;
          }
        }
        
        // 更新总未读数
        this.updateTotalUnreadCount();
      });

      this.socket.onClose(() => {
        console.log('WebSocket连接已关闭');
        this.socket = null;
        
        // 尝试重新连接
        setTimeout(() => {
          this.connectWebSocket();
        }, 3000);
      });

      this.socket.onError((err) => {
        console.error('WebSocket连接错误:', err);
        this.socket = null;
      });
    },

    // 更新总未读数
    updateTotalUnreadCount() {
      let total = 0;
      
      // 计算私聊未读数
      Object.values(this.unreadCounts).forEach(count => {
        if (typeof count === 'number') {
          total += count;
        }
      });
      
      this.unreadCount = total;
    },

    // 获取好友列表
    async fetchFriends() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/api/friend/list',
          method: 'GET',
          header: {
            'satoken': uni.getStorageSync('satoken')
          },
          data: {
            userId: this.userId
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.friends = res.data.data;
        }
      } catch (e) {
        console.error('获取好友列表失败', e);
      }
    },

    // 获取群聊列表
    async fetchGroups() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/api/chat/conversations',
          method: 'GET',
          header: {
            'satoken': uni.getStorageSync('satoken')
          },
          data: {
            userId: this.userId
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.groups = res.data.data
            .filter(conv => conv.conversation && conv.conversation.type === 'GROUP')
            .map(conv => ({
              id: conv.conversation.id,
              name: conv.title || '群聊',
              conversation: conv.conversation,
              group: conv.group || {}
            }));
        }
      } catch (e) {
        console.error('获取群聊列表失败', e);
      }
    },

    // 获取通知列表
    async fetchNotifications() {
      try {
        const res = await uni.request({
          url: 'http://localhost:8080/api/notifications/list',
          method: 'GET',
          header: {
            'satoken': uni.getStorageSync('satoken')
          },
          data: {
            userId: this.userId
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          this.notifications = res.data.data.map(notice => ({
            ...notice,
            createdAt: new Date(notice.createTime || notice.createdAt)
          }));
        }
      } catch (e) {
        console.error('获取通知列表失败', e);
      }
    },

    // 处理私聊
    async openPrivateChat(friend) {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');
        
        // 创建或获取私聊会话
        const res = await uni.request({
          url: `${this.baseUrl}/api/chat/conversation/private?userId=${userId}`,
          method: 'POST',
          header: {
            'satoken': token,
            'Content-Type': 'application/json'
          },
          data: {
            targetUserId: friend.id
          }
        });

        if (res.statusCode === 200 && res.data.status === 10000) {
          const conversationData = res.data.data;
          
          // 设置当前会话
          this.currentConversation = {
            type: 'PRIVATE',
            title: friend.name,
            targetId: friend.id,
            targetUser: friend,
            conversation: conversationData.conversation
          };
          
          // 清空消息列表，准备加载新消息
          this.messages = [];
          this.currentPage = 1;
          this.hasMoreMessages = true;
          
          // 加载消息
          this.loadMessages();
        } else {
          throw new Error(res.data.message || '创建私聊会话失败');
        }
      } catch (e) {
        console.error('开启私聊失败:', e);
        uni.showToast({
          title: '开启私聊失败',
          icon: 'none'
        });
      }
    },

    // 打开群聊
    openGroupChat(group) {
      if (!group || !group.id) {
        uni.showToast({
          title: '无效的群聊',
          icon: 'none'
        });
        return;
      }

      try {
        // 设置当前会话
        this.currentConversation = {
          id: group.id,
          title: group.name || '群聊',
          type: 'GROUP',
          conversation: group.conversation,
          group: group.group
        };
        
        // 清空消息列表，准备加载新消息
        this.messages = [];
        this.currentPage = 1;
        this.hasMoreMessages = true;
        
        // 加载消息
        this.loadMessages();
      } catch (e) {
        console.error('开启群聊失败:', e);
        uni.showToast({
          title: '开启群聊失败',
          icon: 'none'
        });
      }
    },

    // 关闭聊天
    closeChat() {
      this.currentConversation = null;
      this.messages = [];
    },

    // 加载消息
    async loadMessages() {
      try {
        const token = uni.getStorageSync('satoken');
        const userId = uni.getStorageSync('userid');

        let conversationId;
        console.log('当前会话信息:', this.currentConversation);
        
        if (this.currentConversation.type === 'GROUP') {
          conversationId = this.currentConversation.id;
        } else if (this.currentConversation.type === 'PRIVATE') {
          conversationId = this.currentConversation?.conversation?.id;
        }

        if (!conversationId) {
          console.error('无效的会话ID，当前会话:', this.currentConversation);
          throw new Error('无效的会话ID');
        }

        const res = await uni.request({
          url: `${this.baseUrl}/api/chat/messages/${conversationId}`,
          method: 'GET',
          header: {
            'satoken': token
          },
          data: {
            userId: userId,
            page: this.currentPage - 1,
            size: this.pageSize
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 10000) {
          const newMessages = res.data.data.reverse();
          this.hasMoreMessages = newMessages.length === this.pageSize;
          
          if (this.currentPage === 1) {
            this.messages = newMessages;
          } else {
            this.messages = [...newMessages, ...this.messages];
          }
          
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 300);
          });
        } else {
          throw new Error(res.data.message || '加载消息失败');
        }
      } catch (e) {
        console.error('加载消息失败:', e);
        uni.showToast({
          title: '加载消息失败',
          icon: 'none'
        });
      }
    },

    // 滚动到底部
    scrollToBottom() {
      const pages = getCurrentPages();
      const page = pages[pages.length - 1];
      const query = uni.createSelectorQuery().in(page);
      query.select('.message-wrapper').boundingClientRect(data => {
        if (data) {
          this.scrollTop = data.height;
        }
      }).exec();
    },

    // 处理输入
    handleInput(event) {
      this.messageInput = event.detail.value;
    },

    // 发送消息
    async sendMessage() {
      const messageContent = this.messageInput.trim();
      if (!messageContent) return;

      if (!this.socket || this.socket.readyState !== 1) {
        uni.showToast({
          title: '聊天服务未连接，正在重连...',
          icon: 'none'
        });
        this.connectWebSocket();
        return;
      }

      const messageData = {
        conversationId: this.currentConversation?.id || this.currentConversation?.conversation?.id,
        senderId: this.userId,
        senderName: this.studentName,
        content: messageContent,
        messageType: 'TEXT',
        type: this.currentConversation?.type || 'PRIVATE'
      };

      // 先清空输入框
      this.messageInput = '';
      
      // 立即添加消息到列表
      const newMessage = {
        ...messageData,
        createdAt: new Date()
      };
      this.messages = [...this.messages, newMessage];
      
      // 发送消息并滚动到底部
      this.socket.send({
        data: JSON.stringify(messageData),
        success: () => {
          this.$nextTick(() => {
            setTimeout(() => {
              this.scrollToBottom();
            }, 300);
          });
        },
        fail: (err) => {
          console.error('发送消息失败:', err);
          uni.showToast({
            title: '发送失败',
            icon: 'none'
          });
        }
      });
    },

    // 加载更多消息
    async loadMoreMessages() {
      if (this.hasMoreMessages && !this.isRefreshing) {
        this.currentPage++;
        await this.loadMessages();
      }
    },

    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      await this.loadMoreMessages();
      this.isRefreshing = false;
    },

    // 显示更多选项
    showMoreOptions() {
      // 实现显示更多选项的逻辑
      uni.showActionSheet({
        itemList: ['查看聊天记录', '清空聊天记录', '举报'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              // 查看聊天记录
              break;
            case 1:
              // 清空聊天记录
              this.messages = [];
              break;
            case 2:
              // 举报
              uni.showToast({
                title: '举报功能开发中',
                icon: 'none'
              });
              break;
          }
        }
      });
    },

    // 开始录音
    startRecording() {
      if (this.isRecording) return;
      
      this.isRecording = true;
      this.recorderManager = uni.getRecorderManager();
      
      this.recorderManager.onStart(() => {
        console.log('录音开始');
        this.recordingStartTime = Date.now();
      });
      
      this.recorderManager.onError((error) => {
        console.error('录音错误:', error);
        this.isRecording = false;
        uni.showToast({
          title: '录音失败',
          icon: 'none'
        });
      });
      
      this.recorderManager.start({
        duration: 60000,
        sampleRate: 16000,
        numberOfChannels: 1,
        encodeBitRate: 48000,
        format: 'mp3'
      });
    },

    // 停止录音
    stopRecording() {
      if (!this.isRecording) return;
      
      this.recorderManager.stop();
      this.recorderManager.onStop(async (res) => {
        console.log('录音结束:', res);
        this.isRecording = false;
        
        // 检查录音时长
        const duration = Date.now() - this.recordingStartTime;
        if (duration < 1000) {
          uni.showToast({
            title: '录音时间太短',
            icon: 'none'
          });
          return;
        }
        
        // 上传录音文件
        try {
          const uploadRes = await uni.uploadFile({
            url: 'http://localhost:8080/api/chat/upload/audio',
            filePath: res.tempFilePath,
            name: 'file',
            header: {
              'satoken': uni.getStorageSync('satoken')
            }
          });
          
          const data = JSON.parse(uploadRes.data);
          if (data.status === 10000) {
            // 发送语音消息
            const messageData = {
              conversationId: this.currentConversation?.id || this.currentConversation?.conversation?.id,
              senderId: this.userId,
              senderName: this.studentName,
              content: data.data.url,
              messageType: 'AUDIO',
              type: this.currentConversation?.type || 'PRIVATE',
              duration: Math.round(duration / 1000)
            };
            
            this.socket.send({
              data: JSON.stringify(messageData),
              success: () => {
                // 添加消息到列表
                const newMessage = {
                  ...messageData,
                  createdAt: new Date()
                };
                this.messages = [...this.messages, newMessage];
                
                this.$nextTick(() => {
                  setTimeout(() => {
                    this.scrollToBottom();
                  }, 300);
                });
              },
              fail: (err) => {
                console.error('发送语音消息失败:', err);
                uni.showToast({
                  title: '发送失败',
                  icon: 'none'
                });
              }
            });
          } else {
            throw new Error(data.message || '上传录音失败');
          }
        } catch (e) {
          console.error('上传录音失败:', e);
          uni.showToast({
            title: '上传录音失败',
            icon: 'none'
          });
        }
      });
    },

    // 播放音频
    playAudio(url) {
      const innerAudioContext = uni.createInnerAudioContext();
      innerAudioContext.src = url;
      innerAudioContext.play();
      
      innerAudioContext.onError((res) => {
        console.error('播放语音失败:', res);
        uni.showToast({
          title: '播放语音失败',
          icon: 'none'
        });
      });
    },

    // 处理通知
    handleNotification(notice) {
      if (!notice.read) {
        this.markNotificationAsRead(notice.id);
      }
      
      switch (notice.type) {
        case 'FRIEND_REQUEST':
          uni.navigateTo({
            url: '/pages/friend-request?id=' + notice.id
          });
          break;
        case 'GROUP_INVITE':
          uni.navigateTo({
            url: '/pages/group-invite?id=' + notice.id
          });
          break;
        default:
          uni.showModal({
            title: notice.title,
            content: notice.content,
            showCancel: false
          });
      }
    },

    // 标记通知为已读
    async markNotificationAsRead(notificationId) {
      try {
        await uni.request({
          url: `http://localhost:8080/api/notifications/${notificationId}/read`,
          method: 'PUT',
          header: {
            'satoken': uni.getStorageSync('satoken')
          }
        });
        
        const index = this.notifications.findIndex(n => n.id === notificationId);
        if (index !== -1) {
          this.notifications[index].read = true;
        }
      } catch (e) {
        console.error('标记通知已读失败:', e);
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      const now = new Date();
      const diff = now - date;
      
      if (diff < 60000) return '刚刚';
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`;
      if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`;
      
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
    },

    // 获取最后一条消息
    getLastMessage(friendId) {
      // 这里需要实现获取最后一条消息的逻辑
      return null;
    },

    // 获取群聊最后一条消息
    getLastGroupMessage(groupId) {
      // 这里需要实现获取群聊最后一条消息的逻辑
      return null;
    },

    // 获取待办作业
    async loadPendingAssignments() {
      try {
        const res = await uni.request({
          url: `${this.baseUrl}/api/student-answer/pending-assignments`,
          method: 'GET',
          data: {
            userId: this.userId
          },
          header: {
            'content-type': 'application/json',
            'satoken': uni.getStorageSync('satoken')
          }
        });
        
        if (res.statusCode === 200 && res.data.status === 0) {
          console.log('获取待办作业成功:', res.data);
          this.pendingAssignments = res.data.data || [];
        } else {
          console.error('获取待办作业失败:', res.data);
          this.pendingAssignments = [];
        }
      } catch (err) {
        console.error('请求待办作业失败:', err);
        this.pendingAssignments = [];
      }
    },
    
    // 格式化日期
    formatDate(date) {
      if (!date) return '';
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
    },
    
    // 跳转到作业详情
    goToAssignment(assignment) {
      uni.navigateTo({
        url: `/pages/Assignment/StudentCourseAssignments?courseId=${assignment.courseId}`
      });
    },
  },
  onUnload() {
    // 关闭WebSocket连接
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  }
}
</script>
  
<style>
.index-container {
  min-height: 100vh;
  padding: 20px;
  padding-bottom: 70px; /* 为底部导航留出空间 */
  background-color: #f5f5f5;
  position: relative;
  font-size: 1.1em;
  letter-spacing: 0.05em;
}

.header {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-left: 3px solid #4CAF50;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.welcome {
  font-size: 20px;
  color: #333;
  font-weight: 500;
}

.button-group {
  display: flex;
  gap: 10px;
}

.care-mode-btn {
  background-color: #4CAF50;
  color: #fff;
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 4px;
  border: none;
  height: 32px;
  line-height: 24px;
  margin-right: 10px;
  transition: all 0.3s ease;
}

.care-mode-btn.active {
  background-color: #2E7D32;
}

.logout-btn {
  background-color: #ff4d4f;
  color: #fff;
  font-size: 14px;
  padding: 4px 12px;
  border-radius: 4px;
  border: none;
  height: 32px;
  line-height: 24px;
}

/* 关怀模式样式 */
.care-mode {
  font-size: 1.4em;
  letter-spacing: 0.08em;
  line-height: 1.5;
}

.care-mode .welcome,
.care-mode .section-title,
.care-mode .course-title,
.care-mode .tab-text {
  font-weight: bold;
}

.care-mode .progress-fill,
.care-mode .chart-bar {
  background-color: #ff3300 !important;
}

.care-mode .tab-item.active .tab-text {
  color: #ff3300 !important;
  font-size: 1.2em;
}

.care-mode .message-tab-item.active .tab-text {
  color: #ff3300 !important;
}

.care-mode .message-tab-item.active::after {
  background-color: #ff3300 !important;
  height: 3px;
}

.care-mode .message-avatar,
.care-mode .self .text-message,
.care-mode .send-button {
  background-color: #ff3300 !important;
}

.care-mode .self .text-message:after {
  background: #ff3300 !important;
}

.care-mode .course-item {
  border-left: 6px solid #ff3300;
  background-color: #fff;
  padding: 20px;
  margin-bottom: 15px;
}

.care-mode .course-title {
  color: #000;
  font-size: 1.3em;
}

.care-mode .welcome {
  color: #000;
  font-size: 1.5em;
}

.care-mode .message-input {
  border-width: 3px;
  font-size: 1.2em;
}

.care-mode .header {
  border-left: 6px solid #ff3300;
}

.care-mode .stat-value {
  font-size: 1.5em;
  color: #ff3300;
}

.care-mode .stat-label {
  font-size: 1.2em;
}

.care-mode .button-group {
  display: flex;
  gap: 5px;
}

.care-mode .button-group button {
  font-size: 1em;
  height: 36px;
  line-height: 36px;
  padding: 0 6px;
  width: auto;
  min-width: 60px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: flex;
  align-items: center;
  justify-content: center;
}

.care-mode .care-mode-btn {
  background-color: #ff3300;
  width: auto;
  padding: 0 5px;
  font-size: 0.9em;
  display: flex;
  align-items: center;
  justify-content: center;
}

.care-mode .logout-btn {
  width: auto;
  padding: 0 5px;
  font-size: 0.9em;
  display: flex;
  align-items: center;
  justify-content: center;
}

.care-mode .send-button {
  padding: 0 10px;
  min-width: 50px;
}

.care-mode .section-title {
  font-size: 1.4em;
  color: #000;
  border-bottom: 3px solid #ff3300;
  padding-bottom: 8px;
  margin-bottom: 20px;
}

.care-mode .date-range {
  font-size: 1.2em;
  color: #ff3300;
}

.care-mode .tab-icon {
  width: 30px;
  height: 30px;
}

.care-mode .empty-tip {
  font-size: 1.2em;
}

.content {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  min-height: 200px;
}

/* 课程中心样式 */
.course-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  display: block;
  border-bottom: 2px solid #4CAF50;
  padding-bottom: 5px;
}

.date-range {
  font-size: 14px;
  color: #4CAF50;
}

.course-list {
  margin-bottom: 15px;
}

.course-item {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  border-left: 3px solid #4CAF50;
}

.course-item.completed {
  border-left: 3px solid #52c41a;
}

.course-info {
  margin-bottom: 10px;
}

.course-title {
  font-size: 17px;
  color: #333;
  margin-bottom: 5px;
  display: block;
  font-weight: 500;
}

.course-desc {
  font-size: 14px;
  color: #666;
  display: block;
}

.progress-bar {
  height: 6px;
  background-color: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background-color: #4CAF50;
  border-radius: 3px;
}

.empty-tip {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 16px;
}

.stats-container {
  display: flex;
  justify-content: space-between;
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 15px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #4CAF50;
  display: block;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
  display: block;
}

/* 活跃度图表样式 */
.activity-chart {
  margin-top: 10px;
}

.chart-container {
  height: 250px;
  margin-bottom: 20px;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  position: relative;
}

.chart-bars {
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  height: 200px;
  padding-top: 20px;
}

.chart-bar-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40px;
}

.chart-bar {
  width: 30px;
  background-color: #4CAF50;
  border-radius: 3px 3px 0 0;
  min-height: 1px;
}

.chart-label {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.activity-stats {
  display: flex;
  justify-content: space-around;
  background-color: #F0F7F0;
  border-radius: 10px;
  padding: 20px;
}

/* 底部导航栏样式 */
.tabbar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 60px;
  background-color: #fff;
  display: flex;
  box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
}

.tab-icon {
  width: 26px;
  height: 26px;
  margin-bottom: 4px;
}

.tab-text {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.tab-item.active .tab-text {
  color: #4CAF50;
}

/* 消息中心样式 */
.message-content {
  padding: 0;
  width: 100%;
  background: #fff;
}

.chat-item {
  display: flex;
  align-items: flex-start;
  padding: 20px 15px;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  width: 140%;
  box-sizing: border-box;
  margin: 0;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #4CAF50;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-right: 12px;
  flex-shrink: 0;
}

.chat-info {
  flex: 1;
  width: calc(100% - 62px); /* 头像宽度50px + 间距12px */
  overflow: hidden;
  max-width: none;
}

.top-line {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
  width: 100%;
}

.name {
  font-size: 18px;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 15px;
  max-width: 70%;
}

.time {
  font-size: 14px;
  color: #999;
  white-space: nowrap;
  flex-shrink: 0;
  text-align: right;
  min-width: 60px;
}

.last-message {
  font-size: 24rpx;
  color: #666;
  word-break: break-all;
  word-wrap: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
  max-width: 100%;
}

.care-mode .last-message {
  font-size: 28rpx;
}

/* 消息标签样式 */
.message-tabs {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 0;
  border-bottom: 1px solid #eee;
  width: 100%;
  box-sizing: border-box;
}

.message-tab-item {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 33.33%;
  padding: 15px 0;
  box-sizing: border-box;
}

.tab-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.tab-icon {
  width: 26px;
  height: 26px;
  margin-bottom: 8px;
}

.tab-text {
  font-size: 14px;
  color: #333333;
  line-height: 1.2;
  white-space: nowrap;
}

.message-tab-item.active .tab-text {
  color: #4CAF50;
  font-weight: 500;
}

.message-tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background-color: #4CAF50;
}

/* 聊天界面样式 */
.chat-detail {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #f5f5f5;
  z-index: 999;
  display: flex;
  flex-direction: column;
}

.chat-header {
  height: 88rpx;
  padding-top: 44rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-left: 30rpx;
  padding-right: 30rpx;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 101;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.back-button {
  width: 60rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  color: #666;
  font-size: 28rpx;
}

.chat-title {
  flex: 1;
  text-align: center;
  font-size: 32rpx;
  font-weight: 500;
  margin: 0 20rpx;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  color: #333;
}

.header-actions {
  width: 60rpx;
  height: 44rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: #666;
}

.message-list {
  flex: 1;
  height: calc(100vh - 180rpx);
  margin-top: 132rpx;
  box-sizing: border-box;
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 120rpx;
  background-color: #fff; /* 使用纯白背景 */
}

.message-wrapper {
  padding: 10rpx 20rpx;
}

.message-item {
  display: flex;
  margin-bottom: 30rpx; /* 增加消息间距 */
  align-items: flex-start;
}

.message-item:last-child {
  margin-bottom: 10rpx;
}

.message-item.self {
  flex-direction: row-reverse;
}

.message-avatar {
  width: 70rpx;
  height: 70rpx;
  border-radius: 50%;
  background-color: #4CAF50;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  margin: 0 15rpx; /* 增加头像与消息的间距 */
}

.message-content {
  max-width: 70%; /* 限制消息内容宽度 */
  display: flex;
  flex-direction: column;
}

.self .message-content {
  align-items: flex-end;
}

.message-item:not(.self) .message-content {
  align-items: flex-start;
}

.sender-name {
  font-size: 22rpx;
  color: #999;
  margin-bottom: 6rpx;
  padding: 0 10rpx; /* 添加左右内边距 */
}

.text-message {
  background-color: #f1f3f5; /* 使用浅灰色背景 */
  padding: 16rpx 20rpx;
  border-radius: 4rpx; /* 减小圆角 */
  font-size: 28rpx;
  line-height: 1.4;
  word-break: break-all;
  display: inline-block;
  position: relative;
  max-width: 100%;
  border: none;
  margin: 0 10rpx; /* 添加左右外边距 */
}

.self .text-message {
  background-color: #e8f5e9; /* 浅绿色背景 */
  color: #333;
}

/* 移除气泡尾巴 */
.self .text-message:after,
.text-message:not(.self .text-message):after {
  display: none;
}

.message-time {
  font-size: 20rpx;
  color: #999;
  margin-top: 6rpx;
  padding: 0 10rpx; /* 添加左右内边距 */
}

.self .message-time {
  text-align: right;
}

.message-item:not(.self) .message-time {
  text-align: left;
}

.input-area {
  background-color: #fff;
  padding: 20rpx;
  border-top: 1px solid #f1f3f5; /* 使用更浅的边框颜色 */
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.recording-indicator {
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  text-align: center;
  margin-bottom: 10rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.message-input {
  flex: 1;
  padding: 10rpx 14rpx;
  border: 1px solid #eee;
  border-radius: 36rpx;
  max-height: 60rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
  min-height: 36rpx;
  width: calc(100% - 80rpx);
  margin-right: 10rpx;
}

.input-actions {
  margin-left: 10rpx;
  display: flex;
  align-items: center;
}

.send-button {
  background-color: #4CAF50;
  color: white;
  height: 60rpx;
  border-radius: 30rpx;
  font-size: 28rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
  line-height: normal;
}

.send-button::after {
  border: none;
}

.send-button[disabled] {
  background-color: #a5d6a7 !important;
}

.muted-tip {
  text-align: center;
  padding: 20rpx 0;
  color: #999;
  background-color: #f8f8f8;
}

.role-tag {
  font-size: 24rpx;
  color: #4CAF50;
  margin-left: 10rpx;
}

.care-mode .message-tabs {
  border-bottom: 3px solid #eee;
}

.care-mode .message-tab-item {
  padding: 20px 0;
}

.care-mode .tab-icon {
  width: 35px;
  height: 35px;
  margin-bottom: 10px;
}

.care-mode .tab-text {
  font-size: 1.2em;
  font-weight: bold;
}

.care-mode .chat-item {
  padding: 25px 20px;
  border-bottom: 2px solid #eee;
}

.care-mode .avatar {
  width: 60px;
  height: 60px;
  font-size: 24px;
  margin-right: 15px;
}

.care-mode .name {
  font-size: 1.3em;
  font-weight: bold;
  color: #000;
}

.care-mode .time {
  font-size: 1.1em;
  color: #666;
}

.care-mode .last-message {
  font-size: 1.2em;
  color: #333;
  margin-top: 8px;
}

.care-mode .message-avatar {
  width: 60px;
  height: 60px;
  font-size: 24px;
}

.care-mode .text-message {
  font-size: 1.2em;
  padding: 15px 20px;
  line-height: 1.5;
}

.care-mode .message-time {
  font-size: 1.1em;
  margin-top: 8px;
}

.care-mode .message-input {
  font-size: 1.2em;
  padding: 15px;
  border-width: 2px;
}

.care-mode .send-button {
  height: 45px;
  font-size: 1.2em;
  padding: 0 20px;
}

.care-mode .empty-tip {
  font-size: 1.2em;
  padding: 30px;
  text-align: center;
  color: #666;
}

/* 作业中心样式 */
.homework-section {
  margin-bottom: 20px;
}

.homework-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.homework-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-left: 3px solid #4CAF50;
}

.homework-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.homework-icon-text {
  color: #333;
  font-size: 14px;
}

.homework-content {
  flex: 1;
}

.homework-title {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  margin-bottom: 5px;
  display: block;
}

.homework-course {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
  display: block;
}

.homework-deadline {
  font-size: 12px;
  color: #999;
  display: block;
}

.homework-arrow {
  font-size: 20px;
  color: #999;
  margin-left: 10px;
}

/* 关怀模式下的作业中心样式 */
.care-mode .homework-section {
  margin-bottom: 30px;
}

.care-mode .homework-item {
  padding: 20px;
  border-left: 6px solid #ff3300;
}

.care-mode .homework-icon {
  width: 50px;
  height: 50px;
  margin-right: 20px;
}

.care-mode .homework-icon-text {
  font-size: 16px;
}

.care-mode .homework-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.care-mode .homework-course {
  font-size: 16px;
  margin-bottom: 8px;
}

.care-mode .homework-deadline {
  font-size: 14px;
}

.care-mode .homework-arrow {
  font-size: 24px;
}
</style>
  